from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
import os
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

# 初始化扩展
db = SQLAlchemy()

def create_app():
    app = Flask(__name__)
    
    # 配置
    app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'dev')
    app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URL')
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.url_map.strict_slashes = False # 禁用严格斜杠匹配
    
    # 初始化扩展
    CORS(app, resources={r"/api/*": {
        "origins": "http://localhost:8080",
        "methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
        "allow_headers": ["Content-Type"],
        "supports_credentials": True  # 允许跨域请求携带 cookie
    }})
    db.init_app(app)
    
    # 注册蓝图
    from .routes import auth, employee, department, salary, dashboard
    app.register_blueprint(auth.bp)
    app.register_blueprint(employee.bp)
    app.register_blueprint(department.bp)
    app.register_blueprint(salary.bp)
    app.register_blueprint(dashboard.bp)
    
    # 创建数据库表
    with app.app_context():
        db.create_all()
    
    return app 